package org.tigr.htc.request;

/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

import java.io.File;

import org.apache.log4j.Logger;
import org.tigr.antware.shared.testing.TIGRTestCase;
import org.tigr.htc.cmd.CmdState;
import org.tigr.htc.server.IJobMonitor;

public class SgeMockServerTest
    extends TIGRTestCase {
    static Logger log = Logger.getLogger(SgeMockServerTest.class);  
    static IJobMonitor monitor = null;

    public SgeMockServerTest(String name) {
        super(name);
    }

    public void setUp() {
    	;
    }

    public void testSubmit() throws Throwable {
        IRequest req = RequestFactory.newRequest();

        // Create Command
        log.debug("Create Command.");
        req.setCommand(System.getProperty("sgeRoot") + "/examples/jobs/sleeper.sh");
        String home = System.getProperty("user.home");
        req.setInitialDir(home);
        req.setOutput("test.out");
        req.setError("test.err");
        req.addParam("60");
        log.debug(req.toXML());
        
        // Submit the request
        long id = req.submit();
        log.debug("Returned ID: " + id);
        req.waitForRequest();
        assertTrue(req.getState() == CmdState.FINISHED);
    }

    public void testSubmitAndStop() throws Throwable {
        HTCRequest req = (HTCRequest) RequestFactory.newRequest();
        
        // Create Command
        log.debug("Create Command.");
        req.setCommand(System.getProperty("sgeRoot") + "/examples/jobs/sleeper.sh");
        String home = System.getProperty("user.home");
        req.setInitialDir(home);
        req.setOutput("test.out");
        req.setError("test.err");
        req.addParam("500");
        log.debug(req.toXML());
        
        // Submit the request
        long id = req.submit();
        log.debug("Returned id: " + id);
        // Sleep to allow the runner to have started and the Command id to have been
        // assigned
        try {
            Thread.sleep(10000);
        }
        catch (InterruptedException e) {}
        
        // Call the method to stop the job
        req.stop();
        
        req.waitForRequest();
        assertTrue(req.getState() == CmdState.INTERRUPTED);
    }


    /**
     * The <code>waitForCommand</code> method monitor's waits for a file with the command
     * name to be created. When the file becomes available this method exits the loop and 
     * deletes the file.
     */
    protected void waitForCommand(String commandFile) throws Throwable {
        log.info("Will start monitoring for the file creation of file " + commandFile);
        String cmdFileName = commandFile.replaceAll("\\s", "_");
        boolean monitoring = true;
        while (monitoring) {            
            Thread.sleep(1000); // Sleep for a bit before checking again
            log.debug("Waiting for Command file '" + cmdFileName + "' creation.");

            File cmdFile = new File(cmdFileName);
            if (cmdFile.exists()) {
                if (log.isDebugEnabled()) {
                    log.debug("Found file " + cmdFileName);
                }
                monitoring = false;
            }
        }
        
        // Sleep for a little bit to give the client time to finish flushing state
        log.debug("Finished waiting for Command " + commandFile);
        Thread.sleep(10000);
    }
    
    public void testReconnect () throws Throwable {
        HTCRequest req = (HTCRequest) RequestFactory.newRequest();

        // create command
        log.debug("Create Command.");
        String home = System.getProperty("user.home");
        req.setCommand(home + "/create_file.sh");
        req.setInitialDir(home);
        req.setOutput("test.out");
        req.setError("test.err");
        req.addParam("test_reconnect");
        log.debug(req.toXML());
        
        // Delete the test_reconnect file if it exists
        File file = new File(home + "/test_reconnect");
        if (file.exists()) {
            file.delete();
        }
        
        // Submit the request
        long id = req.submit();
        log.debug("Returned id: " + id);
        
        // Wait for the command to be complete
        waitForCommand(home + "/test_reconnect");
        
        // Sleep to allow the runner to have been removed by monitoring threads
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        	// ignored
        }
        
        // Try and reconnect to the command
        log.debug("Attempting to reconnect.");
        long htcJobID = req.cmd.getID();
        RequestFactory.reconnect(htcJobID);
        
        // Wit for request to finish
        req.waitForRequest();
        
        assertTrue(req.getState() == CmdState.FINISHED);
    }

    public static void main(String[] args) throws Throwable {
        String className = "org.tigr.htc.request.SgeMockServerTest";
        TIGRTestCase.testedClass = Class.forName(className);

        // Parse the arguments and set the log level using the value if specified
        // otherwise it is set to 0
        TIGRTestCase.parseArguments(className, args);

        // Call the method in the parent class with the required parameters
        TIGRTestCase.runTestsFromCommandLine(className, args);
        
        // Set the set active flag of the monitor to false
        monitor.setActive(false);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        	// ignored
        }
    } // end of main()
}
